//
//  CustomHeader.swift
//  刷新头
//
//  Created by mini on 2025/4/28.
//

import Foundation

class CustomHeader: MJRefreshGifHeader {

    private let rotateImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "icon_refresh_image"))
        return imageView
    }()
    
    override func prepare() {
        super.prepare()
        stateLabel?.isHidden = true
        lastUpdatedTimeLabel?.isHidden = true

        rotateImageView.contentMode = .scaleAspectFit
        rotateImageView.frame = CGRect(x: (bounds.width - 26) / 2, y: (bounds.height - 26) / 2, width: 26, height: 26)
        rotateImageView.centerX = SCREEN_WIDTH / 2
        addSubview(rotateImageView)
        setRotationAnimationForImageView(imageView: rotateImageView)
    }

    override var state: MJRefreshState {
        didSet {
            switch state {
            case .idle, .refreshing:
                startLoadingAnimation()
            default:
                break
            }
        }
    }

    private func startLoadingAnimation() {
        rotateImageView.layer.removeAnimation(forKey: "rotationAnimation")

        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.fromValue = 0
        rotationAnimation.toValue = Double.pi * 2
        rotationAnimation.duration = 1.0
        rotationAnimation.repeatCount = .greatestFiniteMagnitude
        rotationAnimation.isRemovedOnCompletion = false
        rotateImageView.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }
    
    private func setRotationAnimationForImageView(imageView: UIImageView) {
        let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
        rotationAnimation.fromValue = 0
        rotationAnimation.toValue = Double.pi * 2
        rotationAnimation.duration = 1.0
        rotationAnimation.repeatCount = .greatestFiniteMagnitude
        imageView.layer.add(rotationAnimation, forKey: "rotationAnimation")
    }
}
